import Vue from "vue";
import VueRouter from "vue-router";

import { checkHasToken } from "../libs/utils";

import Home from "@/views/home-pages";
// childrens
/** home-childrens */
import HomeChildren from "./home";
import UserChildren from "./user";

const routerPush = VueRouter.prototype.push;

VueRouter.prototype.push = function (location) {
  if (typeof location === "string") {
    let sperator = "&";
    if (location.indexOf("?") === -1) sperator = "?";
    location = location + sperator + "random=" + Math.random();
  }

  return routerPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Home,
    children: [...HomeChildren],
  },
  {
    path: "/user",
    component: () => import("@/views/user-pages"),
    children: [...UserChildren],
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  const isLogined = checkHasToken();

  if (isLogined) {
    if (to.path.slice(0, 5) !== "/user") {
      next();
      return;
    }
    router.replace("/");
  } else {
    if (to.path.slice(0, 5) === "/user") {
      next();
      return;
    }
    router.replace("/user");
  }

  next();
});

export default router;

export { routes };
